package org.bees.cms.web.util.velocity.renderer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bees.cms.web.util.Beans;
import org.bees.cms.web.util.velocity.element.Link;

public class OperateRenderer extends AbstractRenderer {
	private String gap = "&nbsp;&nbsp;";
	private List<Link> links = new ArrayList<Link>();

	@Override
	public void initialize(JSONObject json) throws Exception {
		super.initialize(json);
		gap = json == null ? gap : json.containsKey("gap") ? json.getString("gap") : gap;
		JSONArray array = json == null ? new JSONArray() : json.containsKey("links") ? json.getJSONArray("links") : new JSONArray();
		for (int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			Link link = new Link();
			link.from(object);
			links.add(link);
		}
	}

	@Override
	public String render(Serializable t) throws Exception {
		StringBuilder builder = new StringBuilder();
		for (Link link : links) {
			String value = Beans.getString(t, link.getProperty());
			String href = link.getAction() + (link.getAction().contains("?") ? "&" : "?") + link.getName() + "=" + value;
			link.setHref(href);
			builder.append(link.toHTML()).append(gap);
		}
		return builder.toString();
	}

	@Override
	public void destroy() throws Exception {
		super.destroy();
		links = null;
	}

	public String getGap() {
		return gap;
	}

	public void setGap(String gap) {
		this.gap = gap;
	}

	public List<Link> getLinks() {
		return links;
	}

	public void setLinks(List<Link> links) {
		this.links = links;
	}

}
